import { request, catchException } from "@/util/request";
import { env } from "@/config/config";
import { createParams } from "./devParams";
import wx from "weixin-js-sdk";

async function initConfig(config: ISdkConfig) {
  try {
    let obj = {};
    const { openTagList, jsApiList } = config;
    if (env === "prod") {
      const url = decodeURI(decodeURI(location.href.split("#")[0]));
      const res = await request({
        url: "wechat/service/createParam",
        method: "GET",
        data: { url },
      });
      const {
        appid: appId,
        wxSha1: signature,
        wxnonceStr: nonceStr,
        timestamp,
      } = res.data.content;
      obj = {
        debug: false,
        appId,
        timestamp: timestamp + "",
        nonceStr,
        signature,
      };
    } else {
      const res = await createParams();
      const { appId, signature, nonceStr, timestamp } = res;
      obj = { debug: false, appId, timestamp, nonceStr, signature };
    }
    if (!obj["signature"]) throw new Error("1001/signature 获取失败");
    wx.config({ ...obj, jsApiList, openTagList });
  } catch (error) {
    if (env === "dev") return;
    catchException(error);
  }
}
async function checkStatus() {
  try {
		console.log('check status')
    const res = await new Promise((resolve, reject) => {
      wx.ready(() => {
				resolve("success")
			});
      wx.error((err: any) => {
				reject(err.errMsg)
			});
    });
    return res;
  } catch (error) {
    console.log(`wxReadyError: ${error}`);
  }
}
async function wxScanCode(scanType: TScanType): Promise<any> {
  return await new Promise((resolve, reject) => {
    wx.scanQRCode({
      scanType,
      needResult: 1,
      success: (res: any) => {
        const resArr = res?.resultStr?.split(",");
        const str = scanType.includes("barCode")
          ? resArr[resArr.length - 1]
          : res.resultStr;
        resolve(str);
      },
    });
  });
}

async function wxGetLocation({ type = "gcj02", isHighAccuracy = true }) {
  try {
    const now = Date.now();
    const crtLocation = JSON.parse(
      sessionStorage.getItem("crtLocation") || "{}"
    );
    if (now - (+crtLocation.tsp || 0) < 10 * 60 * 1000) {
      const { latitude, longitude } = crtLocation;
      return { latitude, longitude };
    }
    await initConfig({
      jsApiList: [
        "scanQRCode",
        "getLocation",
        "showMenuItems",
        "updateTimelineShareData",
        "updateAppMessageShareData",
      ],
      openTagList: ["wx-open-launch-weapp"],
    });
    await checkStatus();
    return await new Promise((resolve, reject) => {
      wx.getLocation({
        type, // wgs84
        success: (res) => {
          let { latitude = 0, longitude = 0 } = res;
          // 安卓字符串，ios数字
          latitude = +(+latitude).toFixed(6);
          longitude = +(+longitude).toFixed(6);
          sessionStorage.setItem(
            "crtLocation",
            JSON.stringify({ latitude, longitude, tsp: Date.now() })
          );
          resolve({ latitude, longitude });
        },
        fail: (err) => {
          console.log(err, 22222);
          reject("1001/请开启定位后重试");
          /* uni.showToast({ title: `1001/${JSON.stringify(err)}`, icon: "none" });
        reject(`1001/${JSON.stringify(err)}`); */
        },
      });
    });
  } catch (error) {
    catchException(new Error("1001/请开启定位后重试"));
  }
}

export { initConfig, checkStatus, wxScanCode, wxGetLocation };
